package com.wpg.demo.spring.xml.aop;

import com.wpg.demo.spring.xml.addressbook.domain.AddressBook;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author ChangWei Li
 * @version 2017-02-22 16:23
 */
@Component
@Aspect
public class AOPAspect {

    @Pointcut("execution(public * *(..))")
    private void anyPublic() { }

    @Pointcut("execution(public * com.wpg.demo.spring.xml.addressbook..*(..))")
    private void anyProjectPublic() {}

    @Pointcut("within(com.wpg.demo.spring.xml.addressbook.repository..*)")
    private void anyRepository() { }

    @Around("anyPublic() && anyProjectPublic() && @annotation(com.wpg.demo.spring.xml.aop.TimeCounter)")
    public Object countTime(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object returnValue = pjp.proceed();

        long endTime = System.currentTimeMillis();

        System.out.printf("%s费时:%sms\n", pjp.getSignature().getName(), endTime - startTime);

        return returnValue;
    }

    @Before("anyRepository() && args(addressBook, ..)")
    public void validateDomain(JoinPoint joinPoint, AddressBook addressBook) {
        System.out.printf("%s参数:%s\n", joinPoint.getSignature().getName(), addressBook);
    }

    @AfterThrowing(value = "anyPublic()", throwing = "exception")
    public void catchException(JoinPoint joinPoint, RuntimeException exception) {

    }

}
